package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.query.StrategyQueryObject;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.service.IStrategyService;
import com.github.pagehelper.PageInfo;
import freemarker.core.Configurable;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/regions")
public class RegionController {
    @Autowired
    private IRegionService regionService;
    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private ServletContext context;

    @GetMapping
    public List<Region> queryAll(Integer state){
        return regionService.queryAll(state);
    }

    @GetMapping(value = "{regionId}/strategies",produces = "text/html;charset=utf-8")
    public void listByRegionId(StrategyQueryObject qo, HttpServletResponse response) throws Exception {
        //查询对应地区状态为推荐的攻略
        qo.setPageSize(0);
        qo.setState(Strategy.STATE_COMMEND);
        PageInfo commends = strategyService.queryForList(qo);
        //查询对应地区所有攻略
        qo.setState(null);
        qo.setPageSize(8);
        PageInfo all = strategyService.queryForList(qo);

        Configuration config = new Configuration(Configuration.VERSION_2_3_23);
        config.setDirectoryForTemplateLoading(new File(context.getRealPath("/template")));
        Template template = config.getTemplate("strategyTemplate.ftl", "utf-8");
        Map<String,Object> data = new HashMap<>();
        data.put("commends",commends);
        data.put("all",all);
        template.process(data,response.getWriter());
    }
    @GetMapping(value = "{regionId}/strategies",produces = "application/json;charset=utf-8")
    public PageInfo query(StrategyQueryObject qo) throws Exception {
       qo.setPageSize(8);
       return strategyService.queryForList(qo);
    }
}
